import Request from 'luch-request';
import {
	BASE_URL,
} from '@/env.js'
import store from '@/codecat/store'
import {
	getToken,
	getBelong
} from "@/codecat/utils/auth";
import errorCode from "@/codecat/utils/errorCode";

/**
 * @description 请求基础配置 可直接使用访问自定义请求
 */
const http = new Request({
	baseURL: BASE_URL,
	timeout: 8000,
	// method: 'GET',
	header: {
		// Accept: 'text/json',
		'Content-Type': 'application/json;charset=UTF-8',
		// platform: $platform.name,
	},
});

// 请求时，白名单的路由忽略自动加上的机构id、校区id
const WhiteInstitutionRegexs = [/\/system\/admin\b/, /\/institution\/school\b/];

function isWhiteInstitutionUrl(url) {
	return WhiteInstitutionRegexs.some((e) => e.test(url));
}

/**
 * @description 请求拦截器
 */
http.interceptors.request.use((config) => {
		if (getToken()) {
			config.header["Authorization"] = "Bearer " + getToken();
		}
		if (!config.data) config.data = {};
		// 统一设置学校、机构
		const isLoseInstitution = !!(config.header || {}).isLoseInstitution ||
			isWhiteInstitutionUrl(config.url); // 是否忽略
		if (getBelong() && !isLoseInstitution) {
			const [institution_id, school_id] = getBelong();
			config.data = {
				institution_id,
				school_id,
				...config.data,
			};
		}
		return config;
	},
	(error) => {
		console.log(error);
		return Promise.reject(error);
	})

/**
 * @description 响应拦截器
 */
http.interceptors.response.use(
	(res) => {
		// 未设置状态码则默认成功状态
		const code = res.data.code;
		// 获取错误信息
		const msg = errorCode[code] || res.data.message || errorCode["default"];
		// 二进制数据则直接返回
		// if (
		// 	res.request.responseType === "blob" ||
		// 	res.request.responseType === "arraybuffer"
		// ) {
		// 	return res;
		// }

		if (code === 401) {
			// 在确定已经登录情况下
			store.dispatch("LogOut").then(() => {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			})
			return Promise.reject("登录已过期, 请重新登录");
		} else if (code !== 0) {
			uni.$u.toast(msg, 3000)
			return Promise.reject(res.data);
		} else {
			return res.data;
		}
	},
	(error) => {
		let {
			message
		} = error;
		if (message == "Network Error") {
			message = "网络连接异常";
		} else if (message.includes("timeout")) {
			message = "系统接口请求超时";
		} else if (message.includes("Request failed with status code")) {
			message = "系统接口" + message.substr(message.length - 3) + "异常";
		}
		uni.$u.toast(message, 5000)
		return Promise.reject(error);
	}
)

const request = (config) => {
	return http.middleware(config);
};

export default request;